package com.zhongxi.guoyuan.fragment.beanexchange;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinPost.LogisiticsInfoAdapter;
import com.zhongxi.guoyuan.adapter.personExchangeOrder.PersonExchangeNoPayAdapter;
import com.zhongxi.guoyuan.adapter.personExchangeOrder.PersonExchangeNoReceiveAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.PersonExchangeResult;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsData;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.utils.QRCodeUtils;
import com.zhongxi.guoyuan.view.beanExchange.PersonExchangeActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class ExchangeNoReceiveFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView> {

    @Bind(R.id.pullToRefreshListView)
    PullToRefreshListView mPullToRefreshListView;


    private PersonExchangeNoReceiveAdapter mNoPayAdapter;


    private List<PersonExchangeResult.OrderInfo> mInfoList = new ArrayList<>();
    private String orderCus;
    private String shopInfo;
    private PersonExchangeResult personExchangeResult;
    private String type;
    private int position;
    private String content;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            position=msg.getData().getInt("pos");
            switch (msg.what){
                case 1://获取验证码
                   getDeliveryCode();
                    break;
                case 2://确认消费
                    confirmOrder();
                    break;
                case 3://去投诉
                    showCommentWindow();
                    break;
                case 4:
                    getLogisitics();
                    break;
            }
        }
    };
    private LogisiticsInfoAdapter infoAdapter;


    public ExchangeNoReceiveFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View mView = inflater.inflate(R.layout.fragment_exchange_no_pay, container, false);
        ButterKnife.bind(this, mView);
        return mView;
    }
    @Override
    protected void initView() {
        super.initView();
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshListView.setOnRefreshListener(this);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            getData();
    }

    @Override
    protected void initData() {
        super.initData();
        mNoPayAdapter = new PersonExchangeNoReceiveAdapter(mHandler, getContext());
        mPullToRefreshListView.setAdapter(mNoPayAdapter);
        getData();
    }

    public void getData() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.EXCHANGE_NORECEIVE, null, str, false, null, "get");
    }

    Map<String,String> map=new HashMap<>();
    /***
     * 获取提货码
     */
    private void getDeliveryCode() {
        type="code";
        map.clear();
        map.put("orderid",mInfoList.get(position).getId());
        map.put("shopid",mInfoList.get(position).getShopid());
        getServer(Url.EXCHANGE_DELIVERCODE, map, "", false, null, "post");
    }

    /***
     * 确认收货  确认/已提、消费
     */
    private void confirmOrder(){
        type="confirm";
        map.clear();
        map.put("ordertype",mInfoList.get(position).getOrdertype());
        map.put("orderid",mInfoList.get(position).getId());
        map.put("shopid",mInfoList.get(position).getShopid());

        for (String key:map.keySet()) {
            Log.d("flag", "confirmOrder: "+key+" : "+map.get(key));
        }

        getServer(Url.EXCHANGE_CONFIRMPRDER, map, "", false, null, "post");

    }

    /**
     * 去投诉
     */
    private void showCommentWindow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_to_complaint, null);
        final EditText editText = (EditText) view.findViewById(R.id.etTips_fuwu);
        final TextView textView = (TextView) view.findViewById(R.id.tvNum_fuwu);
        TextView submit = (TextView) view.findViewById(R.id.tv_submit_complaint);
        ImageView cancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        builder.setView(view);
        final AlertDialog dialog = builder.create();

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(context, textView, editable, 150);
            }
        });


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                content = editText.getText().toString().trim();

                if (null != content && !"".equals(content)) {
                    goComplaints(content);
                    dialog.dismiss();
                } else {
                    showShortToast("请输入您的意见！");
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    /***
     * 去投诉
     */
    private void goComplaints(String content) {
        type="complaints";
        map.clear();
        map.put("ordertype",mInfoList.get(position).getOrdertype());
        map.put("orderid",mInfoList.get(position).getId());
        map.put("shopid",mInfoList.get(position).getShopid());
        map.put("content",content);
        for (String key:map.keySet()) {
            Log.d("flag", key+":"+map.get(key));
        }
        getServer(Url.EXCHANGE_COMFLAINTSORDER, map, "", false, null, "post");
    }

    /***
     * 查物流
     */
    private void getLogisitics(){
        type = "logistics";
        map.clear();
        map.put("orderid", mInfoList.get(position).getId());

        getServer(Url.EXCHANGE_LOGISITICSINFO, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson mGson = new Gson();
        if (type.equals("order")){
            personExchangeResult = mGson.fromJson(response, PersonExchangeResult.class);
            MyApplication.getInstance().setSpValue(personExchangeResult.getSafeobj());
            if (personExchangeResult.getCode() == 1) {
                if (mPullToRefreshListView.isRefreshing())
                    mPullToRefreshListView.onRefreshComplete();

                if (pageNum == 1) {
                    mInfoList.clear();
                }

                if (personExchangeResult.getOrderInfo().size()>0){
                    mInfoList.addAll(personExchangeResult.getOrderInfo());
                }else {
                    if (pageNum!=1)
                        pageNum--;
                }

                try {
                    JSONObject mJSONObject=new JSONObject(response);
                    orderCus=mJSONObject.optString("post");
                    shopInfo=mJSONObject.optString("shopInfo");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mNoPayAdapter.setData(mInfoList, orderCus, shopInfo, (PersonExchangeActivity) getActivity());
                mNoPayAdapter.notifyDataSetChanged();
            }
        }else if (type.equals("confirm")){
            BaseResponse mBaseResponse=mGson.fromJson(response,BaseResponse.class);
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
            getData();
        }else if (type.equals("code")){
            BaseResponse result = mGson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            JSONObject resJson = null;
            try {
                resJson = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject orderCus = resJson.optJSONObject("orderCus");
            String deliverycode = orderCus.optString("deliverycode");
            String qrcode = resJson.optString("qrcode");
            showQrCode(deliverycode,qrcode);
        }else if (type.equals("logistics")){
            LogisiticsResult result = mGson.fromJson(response, LogisiticsResult.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (result.getData()!=null){
                LogisiticsData logisitics = result.getData();
                showLogisticsInfo(logisitics);
            }

        }else if (type.equals("complaints")){
            BaseResponse mBaseResponse=mGson.fromJson(response,BaseResponse.class);
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
            showShortToast("投诉成功");
        }
    }

    /**
     * 查看提货码
     * @param deliverycode
     * @param qrcode
     */
    private void showQrCode(String deliverycode, String qrcode) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_to_qrcode, null);
        final EditText editText = (EditText) view.findViewById(R.id.etTips_fuwu);

        final TextView submit = (TextView) view.findViewById(R.id.tv_submit_complaint);
        ImageView cancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        final ImageView code = (ImageView) view.findViewById(R.id.iv_qrcode);

        builder.setView(view);
        final AlertDialog dialog = builder.create();

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();


        editText.setText("提货码：" + deliverycode);
        code.setVisibility(View.VISIBLE);
        code.setImageBitmap(QRCodeUtils.createQRCode2(qrcode, 200));
        submit.setVisibility(View.GONE);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    /**
     * 物流时间轴
     */
    private void showLogisticsInfo(LogisiticsData logisitics) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.post_show_logisitics, null);
        ImageView back = (ImageView) view.findViewById(R.id.post_logisitics_back);
        TextView company = (TextView) view.findViewById(R.id.post_logisitics_company);
        TextView number = (TextView) view.findViewById(R.id.post_logisitics_number);
        ListView list = (ListView) view.findViewById(R.id.post_logisitics_list);
        TextView error = (TextView) view.findViewById(R.id.logisitics_error);
        builder.setView(view);

        final AlertDialog dialog = builder.create();

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        if(null!=logisitics.getShipper()&&!"".equals(logisitics.getShipper())){
            company.setText("快递公司:" + logisitics.getShipper());
            number.setText("运单编号:" + logisitics.getLogisticCode());
            infoAdapter = new LogisiticsInfoAdapter(getContext());
            list.setAdapter(infoAdapter);
            List<LogisiticsData.Traces> traces = logisitics.getTraces();
            Collections.reverse(traces);
            infoAdapter.setList(traces);
            list.setVisibility(View.VISIBLE);
            error.setVisibility(View.GONE);
        }else{
            if (logisitics.getState().equals("4")) {
                list.setVisibility(View.GONE);
                error.setVisibility(View.VISIBLE);
            }
        }

        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display defaultDisplay = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
        attributes.height = (int) (defaultDisplay.getHeight() * 0.7);
        dialog.getWindow().setAttributes(attributes);
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson=new Gson();
        BaseResponse mBaseResponse=gson.fromJson(response,BaseResponse.class);
        if(null!=mBaseResponse.getSafeobj()&&!"".equals(mBaseResponse.getSafeobj())){
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
        }
        if (mBaseResponse.getCode()==1558){
            showShortToast("您已投诉，不可重复投诉");
        }
        if (mBaseResponse.getCode()==2016){
            showShortToast("订单信息丢失");
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getData();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getData();
    }
}
